<script lang="ts">
	import { EDGE_TYPE, type EdgeInfo as RoadmapEdgeInfo } from '$lib/api/proto/roadmap_data_api';
	import {
		getBezierPath,
		getSmoothStepPath,
		BaseEdge,
		type EdgeProps,
		getStraightPath,
		EdgeLabel
	} from '@xyflow/svelte';
	import { PenLine } from 'lucide-svelte';
	import { roadmapStore } from '../store.svelte';

	const props: EdgeProps = $props();

	const edgeData = $derived(props.data as unknown as RoadmapEdgeInfo);

	let edgePath = $state('');
	let labelX = $state(0);
	let labelY = $state(0);

	$effect(() => {
		if (edgeData.basicInfo?.edgeType == EDGE_TYPE.EDGE_TYPE_BEZIER) {
			const [tmpEdgePath, tmpLabelX, tmpLabelY] = getBezierPath({
				sourceX: props.sourceX,
				sourceY: props.sourceY,
				sourcePosition: props.sourcePosition,
				targetX: props.targetX,
				targetY: props.targetY,
				targetPosition: props.targetPosition
			});
			edgePath = tmpEdgePath;
			labelX = tmpLabelX;
			labelY = tmpLabelY;
		} else if (edgeData.basicInfo?.edgeType == EDGE_TYPE.EDGE_TYPE_SMOOTH_STEP) {
			const [tmpEdgePath, tmpLabelX, tmpLabelY] = getSmoothStepPath({
				sourceX: props.sourceX,
				sourceY: props.sourceY,
				sourcePosition: props.sourcePosition,
				targetX: props.targetX,
				targetY: props.targetY,
				targetPosition: props.targetPosition
			});
			edgePath = tmpEdgePath;
			labelX = tmpLabelX;
			labelY = tmpLabelY;
		} else if (edgeData.basicInfo?.edgeType == EDGE_TYPE.EDGE_TYPE_STEP) {
			const [tmpEdgePath, tmpLabelX, tmpLabelY] = getSmoothStepPath({
				sourceX: props.sourceX,
				sourceY: props.sourceY,
				sourcePosition: props.sourcePosition,
				targetX: props.targetX,
				targetY: props.targetY,
				targetPosition: props.targetPosition,
				borderRadius: 0,
				offset: 0
			});
			edgePath = tmpEdgePath;
			labelX = tmpLabelX;
			labelY = tmpLabelY;
		} else if (edgeData.basicInfo?.edgeType == EDGE_TYPE.EDGE_TYPE_STRAIGHT) {
			const [tmpEdgePath, tmpLabelX, tmpLabelY] = getStraightPath({
				sourceX: props.sourceX,
				sourceY: props.sourceY,
				targetX: props.targetX,
				targetY: props.targetY
			});
			edgePath = tmpEdgePath;
			labelX = tmpLabelX;
			labelY = tmpLabelY;
		}
	});
</script>

<BaseEdge
	path={edgePath}
	markerStart={props.markerStart}
	markerEnd={props.markerEnd}
	style={`stroke-width: ${props.selected ? 3 : 1}px; stroke: var(--color-accent);`}
/>

<EdgeLabel x={labelX} y={labelY} style={props.labelStyle}>
	{edgeData.basicInfo?.label}
	{#if roadmapStore.roadmapMode == 'edit'}
		<button
			class="btn btn-ghost btn-small p-1"
			onclick={() => (roadmapStore.editEdge = edgeData.edgeKey ?? null)}
		>
			<PenLine size={14} />
		</button>
	{/if}
</EdgeLabel>
